#include "widget.h"
#include "ui_widget.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QJsonArray>

#include <addform.h>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    // 程序启动时直接发送请求
    QString url = "http://192.168.124.54:8088/school/api/v1.0/student";
    manager->get(QNetworkRequest(QUrl(url)));

    // 处理服务器的响应结果（响应体）
    connect(manager, &QNetworkAccessManager::finished, [this](QNetworkReply *reply){
        QByteArray jsonStr = reply->readAll();
        QJsonObject jsonObj = QJsonDocument::fromJson(jsonStr).object();
        QJsonArray infoArray = jsonObj.value("data").toArray();

        ui->tableWidget->setRowCount(infoArray.size());
        ui->tableWidget->setColumnCount(infoArray[0].toObject().size() - 2);
        ui->tableWidget->setHorizontalHeaderLabels({"学号", "姓名", "昵称", "性别", "年龄", "入学时间", "所属学院"});

        int row = 0;
        for(QJsonValue item: infoArray)
        {
            QJsonObject stu = item.toObject();
            ui->tableWidget->setItem(row, 0,  new QTableWidgetItem(QString::number(stu.value("sno").toInt())));
            ui->tableWidget->setItem(row, 1,  new QTableWidgetItem(stu.value("sname").toString()));
            ui->tableWidget->setItem(row, 2,  new QTableWidgetItem(stu.value("snickname").toString()));
            ui->tableWidget->setItem(row, 3,  new QTableWidgetItem(stu.value("sgender").toString()));
            ui->tableWidget->setItem(row, 4,  new QTableWidgetItem(QString::number(stu.value("sage").toInt())));
            ui->tableWidget->setItem(row, 5,  new QTableWidgetItem(stu.value("stime").toString()));
            ui->tableWidget->setItem(row++, 6,  new QTableWidgetItem(stu.value("dname").toString()));
        }
    });

    // 点击添加按钮，弹出添加表单
    AddForm *form = new AddForm;
    connect(ui->pushButton, &QPushButton::clicked, [form](){
        form->show();
    });

    connect(form, &AddForm::addOk, [manager, url](){
       manager->get(QNetworkRequest(QUrl(url)));
    });
}

Widget::~Widget()
{
    delete ui;
}
